package com.meitianhui.convenitenbuy.module.mine.presenter;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.hyphenate.HyphenateHelper;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.module.mine.contract.MineContract;
import com.meitianhui.convenitenbuy.module.mine.http.MineApiDataSource;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerAddress;
import com.meitianhui.convenitenbuy.module.mine.model.ConsumerInfo;
import com.meitianhui.convenitenbuy.module.mine.model.LogOutBean;
import com.meitianhui.convenitenbuy.module.mine.model.UserInfo;
import com.meitianhui.convenitenbuy.module.mine.ui.fragment.MineFragment;
import com.meitianhui.convenitenbuy.push.PushUtils;
import com.meitianhui.convenitenbuy.util.AddressUtil;
import com.meitianhui.convenitenbuy.util.BlurImageUtil;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.widget.dialog.ShareDialog;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by amy on 2017/11/2.
 */

public class MinePresenter implements MineContract.Presenter {

    private MineContract.View mView;
    private MineFragment mContext;

    public MinePresenter(MineFragment view, MineFragment context) {
        this.mView = view;
        this.mContext = context;
    }

    public void getUserInfo() {
        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        if (userToken == null) {
            return;
        }
        UserInfo userInfo = InfoProvider.getUserInfo(App.getInstance());
        ConsumerInfo consumerInfo = InfoProvider.getConsumerInfo(App.getInstance());

        Map<String, String> map = new HashMap<>();
        // 原291错误
        map.put("consumer_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        map.put("is_major_addr", "Y");

        MineApiDataSource.getInstance()
                .getUserReceivingAddress(InfoProvider.getAppToken(App.getInstance()),
                        "member.consumerAddressFind", new Gson().toJson(map))
                .subscribe(new ResponseObserver<ConsumerAddress>(mContext.getActivity()) {
                    @Override
                    public void onSuccess(ConsumerAddress consumerAddress) {
                        List<ConsumerAddress.ConsumerData> list = consumerAddress.data;
                        if (list.size() > 0) {
                            String area = getSSQ(list.get(0).getArea_id());
                            String address = list.get(0).getAddress();
                            mView.getUserInfoSuccess(userInfo, consumerInfo, area + address);
                        } else {
                            mView.getUserInfoSuccess(userInfo, consumerInfo, "");
                        }
                    }
                });
    }

    private String getSSQ(String all_id) {
        String address_path = "";

        if (!TextUtils.isEmpty(address_path)) {
            // 这里是做了数据库缓存的  可暂时忽略
            String[] d_address_path = address_path.split(",");
            if (d_address_path.length == 4) {
                String path1 = d_address_path[1];
                String path2 = d_address_path[2];
                String path3 = d_address_path[3];
                if (path2.contains(path1)) {
                    return path2 + path3;
                }
                return path1 + path2 + path3;
            } else {
                return address_path;
            }
        } else {
            return AddressUtil.getRegionData(mContext.getActivity(), all_id);
        }
    }

    public void imgUrl2Bitmap(String doc_path) {
        Observable.create(new ObservableOnSubscribe<Bitmap>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Bitmap> e) throws Exception {
                Bitmap bitmap = BlurImageUtil.returnBitmap(doc_path);
                e.onNext(bitmap);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull Bitmap bitmap) {
                        // 将图片转换成blur的形式
                        Bitmap blurBitmap = BlurImageUtil.BoxBlurFilter(bitmap);
                        mView.setUserBackground(blurBitmap);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Bitmap bitmap = BitmapFactory.decodeResource(
                                mContext.getResources(), R.mipmap.walletandmy_bg);
                        mView.setUserBackground(bitmap);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 第三方分享的回调
     */
    @Override
    public ShareDialog.OnShareClickListener shareListener(UMImage umImage,
                                                          UMShareListener shareListener) {
        ShareDialog.OnShareClickListener onShareClickListener = new ShareDialog.OnShareClickListener() {
            @Override
            public void FriendCircle(View v) {
                UMWeb web = new UMWeb("http://mps-static.meitianhui.com/application/bdsh.html?member_id="
                        + InfoProvider.getUserToken(App.getInstance()).getMember_id()
                        + "&type=friendcircle");
                web.setTitle(mContext.getResources().getString(R.string.app_name));//标题
                web.setThumb(umImage);  //缩略图
                web.setDescription("百万优品，免费领回家");//描述

                new ShareAction(mContext.getActivity())
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
                        .withMedia(web)
                        .share();
                mView.dismissDialog();
            }

            @Override
            public void WeChatFriends(View v) {
                UMWeb web = new UMWeb("http://mps-static.meitianhui.com/application/bdsh.html?member_id="
                        + InfoProvider.getUserToken(App.getInstance()).getMember_id()
                        + "&type=wechatfriends");
                web.setTitle(mContext.getResources().getString(R.string.app_name));//标题
                web.setThumb(umImage);  //缩略图
                web.setDescription("百万优品，免费领回家");//描述
                new ShareAction(mContext.getActivity())
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(shareListener)
                        .withMedia(web)
                        .share();
            }

            @Override
            public void QQFriends(View v) {
                UMWeb web = new UMWeb("http://mps-static.meitianhui.com/application/bdsh.html?member_id="
                        + InfoProvider.getUserToken(App.getInstance()).getMember_id()
                        + "&type=qqfriends");
                web.setTitle(mContext.getResources().getString(R.string.app_name));//标题
                web.setThumb(umImage);  //缩略图
                web.setDescription("百万优品，免费领回家");//描述

                new ShareAction(mContext.getActivity())
                        .setPlatform(SHARE_MEDIA.QQ)
                        .setCallback(shareListener)
                        .withMedia(web)
                        .share();
            }

            @Override
            public void QQZone(View v) {
                UMWeb web = new UMWeb("http://mps-static.meitianhui.com/application/bdsh.html?member_id="
                        + InfoProvider.getUserToken(App.getInstance()).getMember_id()
                        + "&type=qqzone");
                web.setTitle(mContext.getResources().getString(R.string.app_name));//标题
                web.setThumb(umImage);  //缩略图
                web.setDescription("百万优品，免费领回家");//描述

                new ShareAction(mContext.getActivity())
                        .setPlatform(SHARE_MEDIA.QZONE)
                        .setCallback(shareListener)
                        .withMedia(web)
                        .share();
            }

            @Override
            public void WxMini(View v) {
            }
        };

        return onShareClickListener;
    }

    @Override
    public void logOut() {
        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        if (userToken == null) {
            return;
        }

        // 退出环信登录
        HyphenateHelper.getInstance().logout(false, new EMCallBack() {
            @Override
            public void onSuccess() {
                MineApiDataSource.getInstance()
                        .logOut(InfoProvider.getUserToken(App.getInstance()).getUser_token())
                        .subscribe(new ResponseObserver<Object>(mContext.getActivity()) {
                            @Override
                            public void onSuccess(Object o) {
                                PreferenceUtils.clearKey(mContext.getActivity(), Constants.LOGIN_STATUS);
                                PreferenceUtils.clearKey(mContext.getActivity(), Constants.APP_TOKEN_KEY);
                                PreferenceUtils.clearKey(mContext.getActivity(), Constants.USER_RECEIVING_ADDRESS);
                                PushUtils.setAlias(mContext.getActivity(), "", null);
                                PushUtils.setTags(mContext.getActivity(), null, null);
                                // 跳到首页
                                RxBus.get().post(new LogOutBean("logout"));
                            }
                        });
            }

            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
